<template>
  <view class="index">
    <view class="topBox">
      <view class="topBg">
      </view>
    </view>

    <view class="middleOpcition">
      <view class="addGlassBox" v-for="(item, index) in galssTable" :key="item.t_code">
          <view class="imgBox">
           <image  :src="item.t_type_img"/>
          </view>
          <view class="glassInfo">
            <view class="glassTitle">{{item.t_type_name}}</view>
            <view class="glassPs">适用于{{ item.t_target_customers }}</view>
            <view class="glassPrice">¥{{item.t_cost_price}}/副</view>
          </view>
          <view class="glassAddNum">
            <AtInputNumber
              disabledInput
              :width="80"
              :min="0"
              :max="LimitNum['num' + (index+1)]"
              :step="1"
              v-model:value="item.num"
              @tap="getNums"
            />
          </view>
      </view>
    </view>
    <view class="shoppingCart" :class="totalNum > 0? 'shoppingCartMoveUp' : 'shoppingCartMoveDown'">
      <view class="leftContain">
        <view class="cart">
          <view class="glassNum">{{ totalNum }}</view>
        </view>
        <view class="goodsValue">¥{{ totalPrice }}<text class="specialVal"> (押金)</text></view>
      </view>
      <view class="rightContain">
        <AtButton type="primary" @click="gotoGetGlass">下单</AtButton>
      </view>
    </view>
    <view class="fabIcon" v-if="userLogin">
      <AtFab @click="goToGetCode">
        <text class='at-fab__icon' style="font-size: 36rpx; line-height: 48rpx; width: 116rpx; color: #ffffff">取镜</text>
      </AtFab>
    </view>
    <view class="fabIcon_advise" v-if="userLogin">
      <AtFab @click="gotoAdvise">
        <text class='at-fab__icon at-icon at-icon-message'></text>
      </AtFab>
    </view>
    <AtActionSheet
      cancelText='暂不取镜'
      :isOpened="openGlassStatus"
      @cancel="openGlassStatus = false"
      @close="openGlassStatus = false"
      title='点击下方订单取镜'
    >
      <AtActionSheetItem v-for="item in getGlassList" @click="gotoGetQRcodeHtml(item.o_order_code)" :key="item.o_order_code">
        <text style="color: #475F94; font-size: 28rpx; margin-left: 20rpx;" v-for="glass in item.o_content" :key="glass">{{ glass.t_type_name + ':' + glass.num + '副' }}</text>
      </AtActionSheetItem>
    </AtActionSheet>
  </view>
</template>

<script setup>
import './index.scss'
import { AtButton, AtInputNumber, AtToast, AtFab,AtActionSheet, AtActionSheetItem  } from 'taro-ui-vue3'
import { glassList, doOrder, queryOrderList } from  '../../http/api'
import Taro, {useDidShow} from '@tarojs/taro'
import { ref, computed, reactive  } from 'vue'
const LimitNum = computed(() => {
  let total = 0
  let obj = {
    num1: 4,
    num2: 4,
    num3: 4
  }
  galssTable.value.forEach((item, index) => {
      total += item.num;
  })
  if (total >= 4) {
    obj.num1 = galssTable.value[0].num
    obj.num2 = galssTable.value[1].num
    obj.num3 = galssTable.value[2].num
  } else {
    obj.num1 = 4
    obj.num2 = 4
    obj.num3 = 4
  }
  return obj
})
const getNums= () => {
  if(totalNum.value >= 4) {
    Taro.showToast({
      title: '每单最多四副眼镜',
      icon: 'none',
      duration: 2000
    })
  }
}
const totalNum = computed(() => {
    let total = 0
    galssTable.value.forEach(item => {
       total += item.num
    })
    return total
})

const totalPrice = computed(() => {
    let total = 0
    galssTable.value.forEach(item => {
       total += item.num * item.t_cost_price
    })
    return total
})
const galssTable = ref([])
const userLogin = ref(false)

const sentOrder = ref([])

// 跳转建议页面

const gotoAdvise = () => {
  Taro.navigateTo({
    url: '/pages/advise/index'
  })
}


async function gotoGetGlass () {
  sentOrder.value = []
  galssTable.value.forEach(item => {
    if (item.num > 0) {
      sentOrder.value.push({t_code: item.t_code, t_target_customers: item.t_target_customers, num: item.num, t_deposit: item.t_deposit, t_type_name: item.t_type_name})
    }
  })
  try {
    if (totalNum.value > 0) {
        if (userLogin.value){
          let codeOrder = await doOrder({order_data : sentOrder.value})
          // 跳转付款页面
          if (codeOrder.code == '1000') {
            Taro.navigateTo({
              url: `/pages/orderDetail/index?o_order_code=${codeOrder.data.o_order_code}&from=index`
            })
          }

        } else {
          Taro.clearStorage()
          Taro.showModal({
            title: '温馨提示',
            confirmText: '去登录',
            content: '您需要登录后才能进行下一步操作，是否确认去登录？',
            success: (res) => {
              if (res.confirm) {
                userLogin.value = false
                Taro.navigateTo({
                  url: `/pages/login/index?order=${JSON.stringify(sentOrder.value)}`
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })

        }

    }else {
      Taro.showToast({
        title: '请先选择眼镜再进行下单',
        icon: 'none',
        duration: 2000
      })
    }

  } catch (e) {
  }
}
function handleNumberChange (value) {
  console.log(value)
}

glassList().then(res => {
  if (res.code == '1000') {
    galssTable.value = res.data
    galssTable.value.forEach((item, index) => {
      item = Object.assign(item , {num: 0})
      let idx = index >= 3 ? 0 : index
      if (!item.t_type_img) {
        item.t_type_img = require(`./imgs/e${idx + 1}.png`)
      }
    })
  }
})
const openGlassStatus = ref(false)
const getGlassList = ref([])
const goToGetCode = () => {
     // 判断是否打开了权限开关
     Taro.getSetting({
      withSubscriptions: true,
      success: (res) => {
        console.log(res)
        if (!res.subscriptionsSetting.mainSwitch
        || (res.subscriptionsSetting.itemSettings && res.subscriptionsSetting.itemSettings['muc9vjys1iMepXj50BPSnwA1UHm3u0Fzg4vr3EAw1F8']) == 'reject'
      ) {
          Taro.showModal({
            title: '温馨提示',
            showCancel: false,
            content: '为了您能接收到退款提醒消息，请打开设置勾选订阅接受通知消息',
            success: function (res) {
              if (res.confirm) {
                Taro.openSetting({
                  success: function (res) {
                    Taro.showModal({title: '温馨提示',
                    content: '订阅消息通知，方便给您退款通知',
                    showCancel: false,
                    success: function (res) {
                      if (res.confirm) {
                        Taro.requestSubscribeMessage({
                          tmplIds: ['muc9vjys1iMepXj50BPSnwA1UHm3u0Fzg4vr3EAw1F8'],
                          complete: function (Subscribe) {
                          }
                        })
                      } else if (res.cancel) {
                        console.log('用户点击取消')
                      }
                    }})
                  }
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        }else {
          Taro.requestSubscribeMessage({
            tmplIds: ['muc9vjys1iMepXj50BPSnwA1UHm3u0Fzg4vr3EAw1F8'],
            complete: function (Subscribe) {

            }
          })
          queryOrderList({page: 1,o_status:1, page_size:100  }).then(res => {
            if (res.code == '1000') {
              getGlassList.value = res.data.data_list;
              if (getGlassList.value.length > 0) {
                openGlassStatus.value = true
              } else {
                Taro.showToast({
                  title: '暂无可取镜订单',
                  icon: 'none',
                  duration: 1000
                })
              }
            }
          })


        }
      }
    })


}
const gotoGetQRcodeHtml = (o_order_code) => {
  Taro.navigateTo({
    url: `/pages/QRCode/index?o_order_code=${o_order_code}`
  })
  openGlassStatus.value = false
}

useDidShow(() => {
  var token_key_obj = Taro.getStorageSync('userData')
  if (token_key_obj){
    userLogin.value = true
  }else {
    userLogin.value = false
  }
  Taro.showShareMenu({
    withShareTicket: true,
    menus: ['shareAppMessage', 'shareTimeline']
  })
})
</script>
